package com.bw.zcb.mvp.view.user;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bw.zcb.R;
import com.bw.zcb.db.UserEntityDao;
import com.bw.zcb.mvp.base.model.BaseEntity;
import com.bw.zcb.mvp.base.view.BaseActivity;
import com.bw.zcb.mvp.contract.PersonContract;
import com.bw.zcb.mvp.di.DaggerPersonComponent;
import com.bw.zcb.mvp.di.PersonModules;
import com.bw.zcb.mvp.model.PersonModel;
import com.bw.zcb.mvp.model.entity.UserEntity;
import com.bw.zcb.mvp.presenter.PersonPresenter;
import com.bw.zcb.network.tool.App;
import com.bw.zcb.utils.ToastUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class PersonActivity extends BaseActivity<PersonPresenter> implements PersonContract.IPersonView, View.OnClickListener {
    private LinearLayout person;
    private ImageView updateImg;
    private TextView updateName;
    private TextView cancel;
    private TextView photo;
    private TextView camera;
    private String path = "";
    private PopupWindow popupWindow;
    private WindowManager.LayoutParams lp;
    private TextView updateSex;
    private TextView sexCancel;
    private PopupWindow popupWindow1;
    private TextView secrecy;
    private View inflate1;
    private TextView man;
    private TextView woman;
    private getBroadcastReceiver getBroadcastReceiver;
    private TextView back;
    private PersonPresenter personPresenter;
    @Override
    public View addStatusView() {
        return f(R.id.person);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.update_img == id) {
            popupWindow = new PopupWindow();
            View inflate = LayoutInflater.from(this).inflate(R.layout.camera_layout, null);

            cancel = inflate.findViewById(R.id.cancel);
            photo = inflate.findViewById(R.id.photo);
            camera = inflate.findViewById(R.id.camera);
            popupWindow.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
            popupWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);

            popupWindow.setOutsideTouchable(true);
            popupWindow.setContentView(inflate);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
//
//            popupWindow.showAtLocation(inflate, Gravity.BOTTOM,0,0);

            popupWindow.setAnimationStyle(R.style.Popupwindow);
            int[] location = new int[2];

            v.getLocationOnScreen(location);
            popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, -location[1]);
            lp = getWindow().getAttributes();
            lp.alpha = 0.3f;
            getWindow().setAttributes(lp);
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    WindowManager.LayoutParams lp = getWindow().getAttributes();
                    lp.alpha = 1f;
                    getWindow().setAttributes(lp);
                    popupWindow.dismiss();
                }
            });
            photo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 101);
                    popupWindow.dismiss();
                }
            });

            camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ToastUtils.showMsg("相机");
                    Intent intent = new Intent();
                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                    //TODO:使用FileProvider保存照片
                    path = "/sdcard/DCIM/Camera" + createName();
                    Uri uri = FileProvider.getUriForFile(PersonActivity.this, "com.bw.zcb", new File(path));
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(intent, 102);
                }
            });
        }
        if (R.id.update_name == id) {
            Intent intent = new Intent(this, NameActivity.class);
            startActivity(intent);

        }
        if (R.id.update_sex == id) {
            popupWindow1 = new PopupWindow();
            inflate1 = LayoutInflater.from(this).inflate(R.layout.sex_layout, null);

            sexCancel = inflate1.findViewById(R.id.sex_cancel);
            secrecy = inflate1.findViewById(R.id.secrecy);
            man = inflate1.findViewById(R.id.man);
            woman = inflate1.findViewById(R.id.woman);

            popupWindow1.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
            popupWindow1.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);

            popupWindow1.setOutsideTouchable(true);
            popupWindow1.setContentView(inflate1);
            popupWindow1.setBackgroundDrawable(new BitmapDrawable());
            popupWindow1.setAnimationStyle(R.style.Popupwindow);
            int[] location = new int[2];

            v.getLocationOnScreen(location);
            popupWindow1.showAtLocation(v, Gravity.BOTTOM, 0, -location[1]);
            lp = getWindow().getAttributes();
            lp.alpha = 0.3f;
            getWindow().setAttributes(lp);
            sexCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    lp = getWindow().getAttributes();
                    lp.alpha = 1f;
                    getWindow().setAttributes(lp);
                    popupWindow1.dismiss();
                }
            });
            secrecy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserEntity unique = App.getInstance().getDaoSesson().queryBuilder(UserEntity.class).where(UserEntityDao.Properties.Id.eq(1))
                            .unique();
                    if (unique!=null){
                        unique.setUser_sex("0");
                    }
                    App.getInstance().getDaoSesson().update(unique);
                    LogUtils.json(unique);
                    updateSex.setText("保密");
                    lp = getWindow().getAttributes();
                    lp.alpha = 1f;
                    getWindow().setAttributes(lp);
                    popupWindow1.dismiss();
                }
            });
            man.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserEntity unique = App.getInstance().getDaoSesson().queryBuilder(UserEntity.class).where(UserEntityDao.Properties.Id.eq(1))
                            .unique();
                    if (unique!=null){
                        unique.setUser_sex("0");
                    }
                    App.getInstance().getDaoSesson().update(unique);
                    LogUtils.json(unique);
                    updateSex.setText("男");
                    lp = getWindow().getAttributes();
                    lp.alpha = 1f;
                    getWindow().setAttributes(lp);
                    popupWindow1.dismiss();
                }
            });
            woman.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserEntity unique = App.getInstance().getDaoSesson().queryBuilder(UserEntity.class).where(UserEntityDao.Properties.Id.eq(1))
                            .unique();
                    if (unique!=null){
                        unique.setUser_sex("1");
                    }
                    App.getInstance().getDaoSesson().update(unique);
                    LogUtils.json(unique);
                    updateSex.setText("女");
                    lp = getWindow().getAttributes();
                    lp.alpha = 1f;
                    getWindow().setAttributes(lp);
                    popupWindow1.dismiss();
                }
            });
        }
        if (R.id.back==id){
            List<UserEntity> list = App.getInstance().getDaoSesson().queryBuilder(UserEntity.class).list();
            p.requestUpDataUser(list.get(0));
            finish();
        }
    }

    private String createName() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyMMdd_HHmmss");
        String format1 = format.format(date);
        return "IMG_" + format1 + ".jpg";
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //相机
        if (requestCode == 102 && resultCode == Activity.RESULT_OK) {
            Glide.with(this).load(path).transform(new CircleCrop()).into(updateImg);
            lp = getWindow().getAttributes();
            lp.alpha = 1f;
            getWindow().setAttributes(lp);
            UserEntity unique = App.getInstance().getDaoSesson().queryBuilder(UserEntity.class).where(UserEntityDao.Properties.Id.eq("1")).unique();
            if (unique!=null){
                unique.setUser_img(path);
            }
            App.getInstance().getDaoSesson().update(unique);
            p.RequestUpload(path);
            LogUtils.json(path);
            popupWindow.dismiss();
            //相册
        } else if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
            String s = "";
            Uri data1 = data.getData();
            Cursor cursor = getContentResolver().query(data1, null, null, null, null);
            if (cursor!=null){
                if (cursor.moveToFirst()){
                    s=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }
            }
            Glide.with(this).load(data1)
                    .transform(new CircleCrop())
                    .into(updateImg);
            lp = getWindow().getAttributes();
            lp.alpha = 1f;

            getWindow().setAttributes(lp);
            UserEntity unique = App.getInstance().getDaoSesson().queryBuilder(UserEntity.class).where(UserEntityDao.Properties.Id.eq("1")).unique();
            if (unique!=null){
                unique.setUser_img(s);
            }
            App.getInstance().getDaoSesson().update(unique);
            p.RequestUpload(s);
            popupWindow.dismiss();
        }

    }

    @Override
    public int bindLayout() {
        return R.layout.activity_person;
    }

    @Override
    public void initView() {
        person = (LinearLayout) findViewById(R.id.person);
        updateImg = (ImageView) findViewById(R.id.update_img);
        updateName = (TextView) findViewById(R.id.update_name);
        updateSex = (TextView) findViewById(R.id.update_sex);
        updateSex.setOnClickListener(this::onClick);
        updateImg.setOnClickListener(this::onClick);
        updateName.setOnClickListener(this::onClick);
        back = (TextView) findViewById(R.id.back);
        back.setOnClickListener(this::onClick);
        StatusView(Color.WHITE);


        List<UserEntity> userEntities = App.getInstance().getDaoSesson().loadAll(UserEntity.class);
        LogUtils.json(userEntities);
        for (int i = 0; i < userEntities.size(); i++) {
            if (userEntities.get(i).getUser_sex().equals("0")){
                updateSex.setText("男");
            }else{
                updateSex.setText("女");
            }
        }
    }

    @Override
    public void initData() {
        personPresenter = new PersonPresenter(new PersonModel(),this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_PHONE_STATE
            }, 101);
        }
        getBroadcastReceiver = new getBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("nickName");
        registerReceiver(getBroadcastReceiver, intentFilter);
        List<UserEntity> list = App.getInstance().getDaoSesson().queryBuilder(UserEntity.class).list();
        if (list.size()!=0){
            updateName.setText(list.get(0).getUser_name());
            if (list.get(0).getUser_sex().equals("0")) {
                updateSex.setText("男");
            }else {
                updateSex.setText("女");
            }
        }
        List<UserEntity> list1 = App.getInstance().getDaoSesson().queryBuilder(UserEntity.class).list();
        Glide.with(this).load(list1.get(0).getUser_img()).into(updateImg);

    }

    @Override
    public void inject() {
        DaggerPersonComponent.builder().personModules(new PersonModules(this)).build().inject(this);
    }

    class getBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("nickName")) {
                String nicek_name = intent.getStringExtra("nick_Name");
                updateName.setText(nicek_name);
                UserEntity unique = App.getInstance().getDaoSesson().queryBuilder(UserEntity.class).where(UserEntityDao.Properties.Id.eq(1))
                        .unique();
                if (unique!=null){
                    unique.setUser_name(nicek_name);
                }
                App.getInstance().getDaoSesson().update(unique);
//                p.requestUpDataUser(unique);
                LogUtils.json(unique);

            }
        }
    }
    @Override
    public void refreshView(BaseEntity baseEntity) {
//        if (baseEntity.status.equals("200")){
//            ToastUtils.showMsg("更新成功");
//        }else {
//            ToastUtils.showMsg(baseEntity.message);
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(getBroadcastReceiver);
    }
}
